<script setup>
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { onShow } from '@dcloudio/uni-app';
import { request } from '@/request/request';
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
const { t } = useI18n()
const currentLang = ref(uni.getStorageSync('language') || 'zh')

// 计算当前是否是维吾尔语
const isUyghur = computed(() => currentLang.value === 'ug')

// 是否处于编辑模式
const isEditing = ref(false)

// 控制弹窗显示
const showDeletePopup = ref(false)
// 要删除的记录信息
const deleteInfo = ref(null)

onShow(() => {
  request.get('ai/record_list').then(res => {
    // console.log('ai/record_list', res);
  })
})


const backClick = () => {
  uni.navigateBack()
}

// 跳转到首页
const goToIndex = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 聊天记录数据
const historyList = ref({
  today: {
    title: '今天',
    list: []
  },
  thisMonth: {
    title: '本月',
    list: []
  },
  thisYear: {
    title: '今年',
    list: []
  }
})

// 跳转到聊天详情页
const goToChatDetail = (chat_id) => {
  uni.navigateTo({
    url: `/pages/chat-detail/chat-detail?chat_id=${chat_id}`
  })
}

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getFullYear().toString().slice(2)}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`
}

// 获取历史记录
onShow(() => {
  request.get('ai/record_list').then(res => {
    if (res.code === 200) {
      // 更新今天的记录
      historyList.value.today.list = res.data.today.map(item => ({
        title: item.content,
        date: formatDate(item.created_at),
        chat_id: item.chat_id
      }))

      // 更新本月的记录
      historyList.value.thisMonth.list = res.data.month.map(item => ({
        title: item.content,
        date: formatDate(item.created_at),
        chat_id: item.chat_id
      }))

      // 更新今年的记录
      historyList.value.thisYear.list = res.data.year.map(item => ({
        title: item.content,
        date: formatDate(item.created_at),
        chat_id: item.chat_id
      }))
    }
  })
})

// 计算属性用于处理多语言
const historyData = computed(() => ({
  today: {
    title: currentLang.value === 'zh' ? '今天' : 'بۈگۈن',
    list: historyList.value.today.list.map(item => ({
      ...item,
      title: currentLang.value === 'zh' ? item.title : translateTitle(item.title)
    }))
  },
  thisMonth: {
    title: currentLang.value === 'zh' ? '本月' : 'بۇ ئاي',
    list: historyList.value.thisMonth.list.map(item => ({
      ...item,
      title: currentLang.value === 'zh' ? item.title : translateTitle(item.title)
    }))
  },
  thisYear: {
    title: currentLang.value === 'zh' ? '今年' : 'بۇ يىل',
    list: historyList.value.thisYear.list.map(item => ({
      ...item,
      title: currentLang.value === 'zh' ? item.title : translateTitle(item.title)
    }))
  }
}))

// 维吾尔语翻译函数（这里简化处理，实际项目中应该有完整的翻译映射）
const translateTitle = (zhTitle) => {
  const translations = {
    '推荐一款婴儿推车': 'بىر ھارۋا تەۋسىيە قىلىڭ',
    '1+1多少': '1+1 قانچە',
    '后端和前端程序序员有什么区别': 'ئارقا سۇپا ۋە ئالدى سۇپا پروگراممىچىلارنىڭ قانداق پەرقى بار',
    '后端和前端程序序员的职业发展路径有什么...': 'ئارقا سۇپا ۋە ئالدى سۇپا پروگراممىچىلارنىڭ كەسپىي تەرەققىيات يولى قانداق...'
  }
  return translations[zhTitle] || zhTitle
}

// 显示删除确认弹窗
const showDeleteConfirm = (groupKey, index) => {
  deleteInfo.value = { groupKey, index }
  showDeletePopup.value = true
}

// 确认删除
const confirmDelete = () => {
  if (deleteInfo.value) {
    const { groupKey, index } = deleteInfo.value
    const chatId = historyList.value[groupKey].list[index].chat_id

    request.delete(`ai/record?chat_id=${chatId}`).then(res => {
      if (res.code === 200) {
        historyList.value[groupKey].list.splice(index, 1)
        uni.showToast({
          title: currentLang.value === 'zh' ? res.message : res.message_uy,
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: currentLang.value === 'zh' ? res.message : res.message_uy,
          icon: 'none'
        })
      }
    }).catch(() => {
      uni.showToast({
        title: currentLang.value === 'zh' ? res.message : res.message_uy,
        icon: 'none'
      })
    })
  }
  showDeletePopup.value = false
  deleteInfo.value = null
}

// 取消删除
const cancelDelete = () => {
  showDeletePopup.value = false
  deleteInfo.value = null
}
</script>

<template>
  <tn-navbar backgroundColor="#fff" fixed>{{ t('history.title') }}
    <template #back>
      <tn-icon name="left" size="40" @click="backClick"></tn-icon>
    </template>
  </tn-navbar>

  <view class="history-page global-font-size" :class="{ 'rtl': isUyghur }">
    <template v-for="(group, key) in historyData" :key="key">
      <view class="history-group" v-if="group.list.length > 0">
        <view class="group-header">
          <text class="group-title">{{ group.title }}</text>
          <text class="edit-btn" @click="toggleEdit">
            {{ isEditing ? (currentLang === 'zh' ? '完成' : 'تامام') : (currentLang === 'zh' ? '编辑' : 'تەھرىر') }}
          </text>
        </view>
        <view class="history-list">
          <view v-for="(item, index) in group.list" :key="index" class="history-item"
            @click="goToChatDetail(item.chat_id)">
            <view class="item-content">
              <text class="item-title">{{ item.title }}</text>
              <text class="item-date">{{ item.date }}</text>
            </view>
            <text v-if="isEditing" class="delete-btn" @click.stop="showDeleteConfirm(key, index)">
              {{ currentLang === 'zh' ? '删除' : 'ئۆچۈرۈش' }}
            </text>
          </view>
        </view>
      </view>
    </template>

    <!-- 空状态 -->
    <view v-if="!Object.values(historyData).some(group => group.list.length > 0)" class="empty-state">
      <view class="empty-text">{{ currentLang === 'zh' ? '还未创建对话' : 'تېخى تارىخىي سۆھبەت يوق' }}</view>
      <view class="create-btn" @click="goToIndex">{{ currentLang === 'zh' ? '去创建' : 'قۇرۇش' }}</view>
    </view>

    <!-- 删除确认弹窗 -->
    <tn-popup v-model="showDeletePopup" open-direction="center">
      <view class="popup-content">
        <view class="popup-title">{{ t('history.clearTitle') }}</view>
        <view class="popup-desc">{{ t('history.clearDesc') }}</view>
        <view class="popup-buttons">
          <view class="btn cancel-btn" @click="cancelDelete">{{ t('history.cancel') }}</view>
          <view class="btn delete-btn" @click="confirmDelete">{{ t('history.delete') }}</view>
        </view>
      </view>
    </tn-popup>
  </view>
</template>

<style lang="scss" scoped>
.history-page {
  min-height: 100vh;
  background-color: #f7f7f7;
  padding: 20rpx;

  &.rtl {
    direction: rtl;
  }
}

.history-group {
  margin-bottom: 40rpx;

  .group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .group-title {
      font-size: 28rpx;
      color: #999;
    }

    .edit-btn {
      color: #0066ff;
      font-size: 28rpx;
    }
  }
}

.history-list {
  .history-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 32rpx;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .item-content {
      flex: 1;
      display: flex;
      justify-content: space-between;

      .item-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 8rpx;
      }

      .item-date {
        font-size: 24rpx;
        color: #999;
      }
    }

    .delete-btn {
      color: #ff3b30;
      font-size: 28rpx;
    }
  }
}

.empty-state {
  text-align: center;
  margin-top: 300rpx;

  .empty-text {
    color: #999;
    font-size: 28rpx;
    margin-bottom: 30rpx;
  }

  .create-btn {
    display: inline-block;
    padding: 20rpx 60rpx;
    background-color: #0066ff;
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
  }
}

.popup-content {
  width: 580rpx;
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;

  .popup-title {
    font-size: 32rpx;
    color: #333;
    text-align: center;
    margin-bottom: 16rpx;
  }

  .popup-desc {
    font-size: 28rpx;
    color: #666;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .popup-buttons {
    display: flex;
    gap: 20rpx;
    align-items: center;
    justify-content: space-around;

    :deep(.tn-button) {
      height: 80rpx !important;
      font-size: 32rpx !important;
    }
  }
}

.delete-btn {
  color: #ff3b30;
  font-size: 28rpx;
}
</style>